// https://www.lintcode.com/problem/average-of-levels-in-binary-tree/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the binary tree of the  root
     * @return: return a list of double
     */
    public List<Double> averageOfLevels(TreeNode root) {
        // write your code here
        List<Double> ret = new ArrayList<>();
        List<TreeNode>[] levels = new List[]{new ArrayList<TreeNode>(), new ArrayList<TreeNode>()};
        int curr = 0;
        levels[curr].add(root);
        while (levels[curr].size() > 0) {
            int sum = 0, next = 1 - curr;
            for (TreeNode node : levels[curr]) {
                sum += node.val;
                if (node.left != null) {
                    levels[next].add(node.left);
                }
                if (node.right != null) {
                    levels[next].add(node.right);
                }
            }
            ret.add((double)sum / (double)(levels[curr].size()));
            levels[curr].clear();
            curr = next;
        }
        return ret;
    }
}